﻿using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace jQuery.Validation.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public sealed class EqualToAttribute : ValidationAttribute
    {
        public string SourceProperty { get; set; }
        public string TargetProperty { get; set; }

        public EqualToAttribute(string sourceProperty, string targetProperty)
        {
            SourceProperty = sourceProperty;
            TargetProperty = targetProperty;
        }

        public override bool IsValid(object value)
        {
            if (value == null)
                return true;

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find(SourceProperty, true /* ignoreCase */).GetValue(value);
            object confirmValue = properties.Find(TargetProperty, true /* ignoreCase */).GetValue(value);
            
            return Object.Equals(originalValue, confirmValue);
            
        }
    }
}
